'use strict'
require('./index.scss')
require('page/common/nav/index.js')
require('page/common/header/index.js')
var navSide = require('page/common/nav-side/index.js')
// 通用的JS工具封装
var _wm = require('util/wm.js')
// 用户服务
var _user = require('service/user-service.js')



var page = {
    init: function(){
        this.onLoad()
        this.bindEvent()
    },

    onLoad: function(){
        // 初始化左侧菜单
        navSide.init({
            name: 'user-pass-update'
        })
    },

    bindEvent: function(){
        var that = this

        // 点击提交按钮后的动作，事件冒泡
        $('.btn_submit').click(function(){
            var passwordInfo = {
                password: $.trim($('#password').val()),
                passwordNew: $.trim($('#password_new').val()),
                passwordConfirm: $.trim($('#password_confirm').val())
            },
            validateResult = that.validateForm(passwordInfo)
            if(validateResult.status){
                // 更改用户密码
                _user.updatePassword({
                    passwordOld: passwordInfo.password,
                    passwordNew: passwordInfo.passwordNew
                }, function(res, msg){
                    _wm.successTips(msg)
                }, function(errMsg){
                    _wm.errorTips(errMsg)
                })
            }else{
                _wm.errorTips(validateResult.msg)
            }
        })
    },
    
    // 验证字段信息
    validateForm: function(formData){
        // 返回的验证结果
        var result = {
            status: false,
            msg: ''
        }
        // 验证原密码不能为空
        if(!_wm.validate(formData.password, 'require')){
            result.msg = '原密码不能为空'
            return result
        }
        // 验证新密码的长度
        if(!formData.passwordNew || formData.passwordNew.length < 6){
            result.msg = '密码长度至少为6位'
            return result
        }
        // 验证2次密码是否一致
        if(formData.passwordNew !== formData.passwordConfirm){
            result.msg = '您输入的2次密码不一致'
            return result
        }

        // 验证通过，返回正确提示
        return result = {
            status: true,
            msg: '验证通过'
        }
    }
}

$(function(){
    page.init()
})